const banner = document.querySelector(".banner");
const canvas = document.querySelector("#dotsCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const ctx = canvas.getContext("2d");

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; //不含最大值，含最小值
}

function randomColor() {
    const colors = [
        "#FFC0CB",
        "#FFA07A",
        "#FFD700",
        "#ADFF2F",
        "#87CEFA",
        "#00BFFF",
        "#00CED1",
        "#1E90FF",
        "#B0C4DE",
        "#FF69B4"
    ];
    return colors[Math.floor(Math.random() * colors.length)];
}

const createDots = () => {
    const dots = [];
    for (let i = 0; i < 100; i++) {
        dots.push({
            x: getRandomInt(0, canvas.width),
            y: getRandomInt(0, canvas.height),
            r: getRandomInt(1, 3),
            color: randomColor()
        });
    }
    return dots;
};
const dots = createDots();

const drawDots = () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    dots.forEach(dot => {
        ctx.beginPath();
        ctx.arc(dot.x, dot.y, dot.r, 0, Math.PI * 2, false);
        ctx.fillStyle = dot.color;
        ctx.fill();
    });
};

drawDots();

const mouseMoveHandler = event => {
    // 鼠标移动后要清除画布，要不然鼠标移开后，画布上还残留着上次画的线条
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 清除画布把点也清除，重新绘制点。因为点信息是固定的，所以能重新画出上次一样的点。
    drawDots();

    const x = event.clientX - canvas.offsetLeft;
    const y = event.clientY - canvas.offsetTop;

    dots.forEach(dot => {
        // 勾股定理求距离
        const distance = Math.sqrt(Math.pow(x - dot.x, 2) + Math.pow(y - dot.y, 2));
        if (distance < 300) {
            // 绘制线条
            // ctx.save();
            ctx.strokeStyle = dot.color;
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(dot.x, dot.y);
            ctx.lineTo(event.clientX, event.clientY);
            ctx.stroke();
            // setTimeout(() => {
            //     // 延迟一段时间后清除线条
              
            //     // 使用 moveTo 和 lineTo 重新描绘线条，但这次使用 'destination-out' 模式来擦除
            //     ctx.globalCompositeOperation = "destination-out";

            //     ctx.moveTo(dot.x, dot.y);
            //     ctx.lineTo(event.clientX, event.clientY);
            //     ctx.stroke();

            //     // 清除完毕后恢复默认的合成模式
            //     ctx.globalCompositeOperation = "source-over";
            // }, 1000);
        }
    });
};

banner.addEventListener("mousemove", mouseMoveHandler);
banner.addEventListener("mouseout", () => {
    // 鼠标移出banner时清除画布，并重新绘制点
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawDots();
});

// export {};
